/*
 * MessageDispatcher.java
 *
 * Created on March 27, 2007, 2:50 PM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package ai9hells.pgaibe.chapter2.westworldwithmessaging;

import java.util.Date;
import java.util.PriorityQueue;
import ai9hells.pgaibe.common.messaging.Telegram;

/**
 *
 * @author andre.bandarra
 */
public class MessageDispatcher {
    public static final MessageDispatcher INSTANCE = new MessageDispatcher();
    private PriorityQueue<Telegram> queue = new PriorityQueue<Telegram>();
    /** Creates a new instance of MessageDispatcher */
    private MessageDispatcher() {
    }
    
    private void discharge(BaseGameEntity entity, Telegram msg){
        if (!entity.handleMessage(msg)){
            System.err.println("Message not Handled");
        }        
    }
    public void dispatchMessage(long delay, int sender, int receiver,
            int msg, Object extraInfo){

        BaseGameEntity bgeSender = EntityManager.INSTANCE.getEntityFromId(sender);
        BaseGameEntity bgeReceiver = EntityManager.INSTANCE.getEntityFromId(receiver);
        if (bgeReceiver == null){
            System.err.println("Warning: No Receiver with ID: "+receiver);
            return;
        }
        Telegram t = new Telegram(sender, receiver,msg, 0 , extraInfo);
        if (delay <= 0){
            System.err.println("Instant telegram dispatched at time: " +
                    new Date() +" by "+EntityNames.getNameOfEntity(sender) +
                    " for "+EntityNames.getNameOfEntity(receiver)+". Msg is: "
                    +MessageTypes.msgToStr(msg)) ;
            discharge(bgeReceiver, t);
            
        } else {
            System.err.println("Delayed telegram recorded at: "+new Date()+
                    " from "+EntityNames.getNameOfEntity(sender)+
                    " to "+EntityNames.getNameOfEntity(receiver)+
                    ". Msg is: "+MessageTypes.msgToStr(msg));
            long dispatchTime = new Date().getTime() + delay;
            t.setDispatchTime(dispatchTime);
            queue.add(t);
        }
        
    }
    public void dispatchDelayedMessages(){
        long curtime =new Date().getTime();
        while (queue.size() > 0 && queue.peek().getDispatchTime() < curtime &&
                queue.peek().getDispatchTime() > 0){
            Telegram t = queue.poll();
            BaseGameEntity receiver = EntityManager.INSTANCE.getEntityFromId(t.getReceiver());
            System.err.println("Queued telegram ready for dispatch: Sent to "+
                    EntityNames.getNameOfEntity(t.getReceiver())+". Msg is: "+
                    MessageTypes.msgToStr(t.getMsg()));            
            discharge(receiver, t);
        }
        
    }
    
}
